import React, {createContext, memo, useState, useEffect} from 'react'
import {
	Button,
	Space,
	Col,
	Row,
	Input,
	Tree,
	message,
	Popconfirm,
	Tag,
	TreeSelect,
	Form,
} from 'antd'
import {ArrowDownOutlined, PlusOutlined} from '@ant-design/icons'
import {connect, history} from 'umi'
import {getDeptList, deleteDept} from '@/service/system/dept'
import {getUsePageList, deleteUser} from '@/service/system/user'
import {getCompany} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'
import CustomTable from '@/components/Table'
import common from '@/assets/common/css/index.less'
import styles from './index.less'
import Permissions from '@/components/Permissions'
import {downloadDocumentUrl} from '@/service/common/download'

export const modalContext = createContext({})
const {TreeNode} = Tree
const {Search} = Input

const DeptAddUserDemo = memo((props: {dispatch: any; user: any}) => {
	const {currentMerchantId, orgId} = props.user
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [deptData, setDeptDataSource] = useState<any>()
	const [userdataSource, setUserDataSource] = useState([])

	const [name, setNameSource] = useState('')
	const [departmentId, setDepartmentId] = useState('')
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [orgSource, setOrgSource] = useState<any>()
	const [form] = Form.useForm()
	// 部门列表
	const getDeptFun = () => {
		setLoading(true)
		getDeptList({merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				if (list.length) {
					setDepartmentId(() => list[0].id.toString())
				} else {
					setDepartmentId(() => '')
				}
				setDeptDataSource(list as any)
			}
		})
	}

	// 用户列表
	const getUserFun = () => {
		setLoading(true)
		if (!departmentId) {
			return false
		}
		getUsePageList({
			merchantId: currentMerchantId,
			...params,
			name: name || '',
			departmentId,
		})
			.then((res: any) => {
				setUserDataSource(res?.data?.records)
				setTotal(res?.data?.total)
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
		return true
	}
	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
				if (!currentMerchantId) {
					form.setFieldsValue({merchantId: list[0]?.id})
				} else {
					form.setFieldsValue({merchantId: currentMerchantId})
				}
			}
		})
	}
	const onDeletFun = (deptId: string) => {
		deleteDept(deptId, currentMerchantId).then((res: any) => {
			if (res?.success) {
				message.success(res.msg)
				setDepartmentId(() => '')
				getDeptFun()
			}
		})
	}

	const init = () => {
		const initParams = {
			current: 1,
			size: 10,
		}
		setParams(() => initParams)
	}
	useEffect(() => {
		init()
	}, [departmentId, name])
	// 删除用户
	const onDeleteUserFun = (userId: string) => {
		deleteUser({userId, merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				message.success(res.msg)
				init()
			}
		})
	}
	const userColumns = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: string, record: any, index: number) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '用户编号',
			key: 'id',
			align: 'center',
			width: 160,
			dataIndex: 'id',
			render: (text: string) => (
				<div className="ellipsis" title={text}>
					{text || '--'}
				</div>
			),
		},
		{
			title: '用户名称',
			key: 'name',
			align: 'center',
			width: 160,
			dataIndex: 'name',
			render: (text: string) => (
				<div className="ellipsis" title={text}>
					{text || '--'}
				</div>
			),
		},
		{
			title: '所属部门',
			key: 'departmentName',
			align: 'center',
			width: 160,
			dataIndex: 'departmentName',
			render: (text: string) => (
				<div className="ellipsis" title={text}>
					{text || '--'}
				</div>
			),
		},
		{
			title: '是否管理员',
			key: 'admin',
			align: 'center',
			width: 150,
			dataIndex: 'admin',
			render: (text: any) => <div>{text === 1 ? '是' : '否'}</div>,
		},
		{
			title: '状态',
			key: 'status',
			align: 'center',
			width: 120,
			dataIndex: 'status',
			render: (text: any) => (
				<div>
					{text === 1 ? (
						<Tag color="processing">正常</Tag>
					) : (
						<Tag color="error">休眠</Tag>
					)}
				</div>
			),
		},
		{
			title: '操作',
			dataIndex: 'option',
			width: 300,
			key: 'option',
			fixed: 'right',
			align: 'center',
			render: (text: any, record: {id: any}) => (
				<div>
					<Permissions permissionID="amc_system_permission_deptAddUser_userEdit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/system/deptAddUser/user/edit',
									query: {
										id: record.id,
									},
								})
							}}>
							修改
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_deptAddUser_userView">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/system/deptAddUser/user/view',
									query: {
										id: record.id,
									},
								})
							}}>
							查看
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_deptAddUser_userShare">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/system/deptAddUser/user/limit',
									query: {
										id: record.id,
									},
								})
							}}>
							分配权限
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_deptAddUser_userDelete">
						<Popconfirm
							placement="topLeft"
							title="你确定要删除该用户？"
							onConfirm={() => onDeleteUserFun(record.id)}
							okText="确定"
							cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</Permissions>
				</div>
			),
		},
	]
	const getTreeNode = (data: any[]) => {
		if (data && data.length > 0) {
			return data.map((item) => {
				if (item.children) {
					return (
						<TreeNode
							key={item.id}
							title={
								<div>
									<span>{item.name}</span>
									<div className="treeBtnList">
										<Permissions permissionID="amc_system_permission_deptAddUser_deptAdd">
											<Button
												type="link"
												size="small"
												onClick={() => {
													history.push({
														pathname:
															'/system/deptAddUser/dept/add',
														query: {
															cid: item.id,
														},
													})
												}}>
												新增
											</Button>
										</Permissions>
										<Permissions permissionID="amc_system_permission_deptAddUser_deptEdit">
											<Button
												type="link"
												size="small"
												onClick={() => {
													history.push({
														pathname:
															'/system/deptAddUser/dept/edit',
														query: {
															id: item.id,
														},
													})
												}}>
												编辑
											</Button>
										</Permissions>
										<Permissions permissionID="amc_system_permission_deptAddUser_deptView">
											<Button
												type="link"
												size="small"
												onClick={() => {
													history.push({
														pathname:
															'/system/deptAddUser/dept/view',
														query: {
															id: item.id,
														},
													})
												}}>
												查看
											</Button>
										</Permissions>
										<Permissions permissionID="amc_system_permission_deptAddUser_deptDelete">
											<Button
												type="link"
												size="small"
												onClick={() =>
													onDeletFun(item.id)
												}>
												删除
											</Button>
										</Permissions>
									</div>
								</div>
							}>
							{getTreeNode(item.children)}
						</TreeNode>
					)
				}
				return (
					<TreeNode
						key={item.id}
						title={
							<div>
								<span>{item.name}</span>
								<div className="treeBtnList">
									<Permissions permissionID="amc_system_permission_deptAddUser_deptAdd">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/system/deptAddUser/dept/add',
													query: {
														cid: item.id,
													},
												})
											}}>
											新增
										</Button>
									</Permissions>
									<Permissions permissionID="amc_system_permission_deptAddUser_deptEdit">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/system/deptAddUser/dept/edit',
													query: {
														id: item.id,
													},
												})
											}}>
											编辑
										</Button>
									</Permissions>
									<Permissions permissionID="amc_system_permission_deptAddUser_deptView">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/system/deptAddUser/dept/view',
													query: {
														id: item.id,
													},
												})
											}}>
											查看
										</Button>
									</Permissions>
									<Permissions permissionID="amc_system_permission_deptAddUser_deptDelete">
										<Popconfirm
											placement="topLeft"
											title="你确定要删除该部门吗？"
											onConfirm={() =>
												onDeletFun(item.id)
											}
											okText="确定"
											cancelText="取消">
											<Button type="link" size="small">
												删除
											</Button>
										</Popconfirm>
									</Permissions>
								</div>
							</div>
						}
					/>
				)
			})
		}
		return []
	}
	// 新增用户
	const addUserFun = () => {
		history.push({
			pathname: '/system/deptAddUser/user/add',
			query: {
				departmentId,
			},
		})
	}

	// 获取公司
	useEffect(() => {
		onOrgFun()
	}, [orgId])

	// 获取部门
	useEffect(() => {
		if (currentMerchantId) {
			getDeptFun()
		}
	}, [currentMerchantId])

	// 获取用户
	useEffect(() => {
		if (currentMerchantId) {
			getUserFun()
		}
	}, [currentMerchantId, params])

	const onUserSearch = (value: string) => {
		setNameSource(() => value)
	}
	// 部门点击事件
	const treeSelectFun = (selectedKeys: any) => {
		if (selectedKeys.length) {
			setDepartmentId(() => selectedKeys[0])
		}
	}

	const onChange = (key: any) => {
		props.dispatch({
			type: 'user/updateCurrentMerchantId',
			payload: {
				currentMerchantId: key,
			},
		})
	}

	return (
		<>
			<Row gutter={12}>
				<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
					<div className={styles.content}>
						<div className="searchForm">
							<Form
								name="basic"
								form={form}
								layout="horizontal"
								labelCol={{flex: '80px'}}
								initialValues={{remember: true}}
								autoComplete="off">
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 12}}>
										<Form.Item
											label="组织机构"
											name="merchantId"
											rules={[{required: true}]}>
											<TreeSelect
												showSearch
												treeNodeFilterProp="name"
												style={{width: '100%'}}
												dropdownStyle={{
													maxHeight: 400,
													overflow: 'auto',
												}}
												placeholder="请输入组织机构"
												treeDefaultExpandAll
												onChange={onChange}
												fieldNames={{
													label: 'name',
													value: 'id',
												}}
												treeData={orgSource}
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</div>
						<div className="btnlist">
							<Space size={12}>
								<Permissions permissionID="amc_system_permission_deptAddUser_deptAdd">
									<Button
										type="primary"
										ghost
										size="small"
										onClick={() => {
											history.push({
												pathname:
													'/system/deptAddUser/dept/add',
												query: {
													cid: departmentId,
												},
											})
										}}>
										新增
									</Button>
								</Permissions>
								<Permissions permissionID="amc_system_permission_deptAddUser_deptExport">
									<Button
										icon={<ArrowDownOutlined />}
										ghost
										size="small"
										className="import"
										onClick={() =>
											downloadDocumentUrl({
												resourceId: '95',
												queryDesc:
													'部门导出,merchantId:公司Id',
												queryParam: {
													merchantId:
														currentMerchantId,
												},
											})
										}>
										导出
									</Button>
								</Permissions>
							</Space>
						</div>

						{deptData && deptData.length > 0 ? (
							<div className="treeborder">
								<Tree
									blockNode
									autoExpandParent
									onSelect={treeSelectFun}
									selectedKeys={[departmentId]}
									defaultExpandAll>
									{getTreeNode(deptData)}
								</Tree>
							</div>
						) : null}
					</div>
				</Col>
				<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
					<div className={common.content}>
						<div className="btnlist">
							<Space size={12}>
								<Permissions permissionID="amc_system_permission_deptAddUser_userAdd">
									<Button
										icon={<PlusOutlined />}
										type="primary"
										ghost
										size="small"
										onClick={addUserFun}>
										新增
									</Button>
								</Permissions>
								<Permissions permissionID="amc_system_permission_deptAddUser_userExport">
									<Button
										icon={<ArrowDownOutlined />}
										ghost
										size="small"
										className="import"
										onClick={() => {
											if (departmentId === '') {
												message.warning(
													'缺少部门ID无法下载',
												)
											} else {
												downloadDocumentUrl({
													resourceId: '96',
													queryDesc:
														'用户导出,merchantId:公司Id,name:用户名称或编号',
													queryParam: {
														merchantId:
															currentMerchantId,
														departmentId,
														name,
													},
												})
											}
										}}>
										导出
									</Button>
								</Permissions>
								<Search
									placeholder="请输入用户名称或编号"
									allowClear
									enterButton="搜索"
									onSearch={onUserSearch}
									style={{width: 300}}
								/>
							</Space>
						</div>
						<CustomTable
							params={params}
							columns={userColumns}
							pagination
							total={total}
							callback={(pagination: any) => {
								setParams(pagination)
							}}
							loading={loading}
							dataSource={userdataSource}
						/>
					</div>
				</Col>
			</Row>
		</>
	)
})

export default connect(({user}: any, {deptAddUser}: any) => ({
	user,
	deptAddUser,
}))(DeptAddUserDemo)
